﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Argotic.Common;
using System.Xml.XPath;
using Argotic.Data.Adapters;
using Argotic.Syndication;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace MyPublish.Connection.Syndication.CSDN
{
    [DataConnectionProvider(Name = "CSDN", Type = typeof(CSDNConnectionProvider))]
    public class CSDNConnectionProvider : DataConnectionProvider
    {
        public const string BLOG_URI = "http://blog.csdn.net/";

        private CSDNMetaWeblog _weblog;
        private CSDNMetaWeblog Weblog
        {
            get
            {
                if (_weblog == null)
                {
                    _weblog = new CSDNMetaWeblog();
                    if (Proxy != null)
                    {
                        _weblog.Credentials = Proxy.Credentials;
                    }
                }
                return _weblog;
            }
        }

        public override IEnumerable<object> ExecuteQuery()
        {
            List<object> items = new List<object>();


            UserBlog[] blogs = null;
            try
            {
                blogs = Weblog.getUsersBlogs(string.Empty, ConnectionString.UserName, ConnectionString.Password);
            }
            catch (Exception e)
            {
                throw new DataConnectionException("Failed to create getUsersBlogs " + ConnectionString.UserName, e);
            }

            foreach (UserBlog blog in blogs)
            {
                HtmlDocument document = null;
                HtmlWeb web = null;
                try
                {
                    web = new HtmlWeb();
                    document = web.Load(blog.url, "GET");
                }
                catch (Exception e)
                {
                    //throw new DataConnectionException("Failed to load url " + blog.url, e);
                    continue;
                }

                string pattern = string.Format(@"/{0}/category/\d+\.aspx/rss", ConnectionString.UserName);
                HtmlNodeCollection linkNodes = document.DocumentNode.SelectNodes("//a");
                foreach (HtmlNode linkNode in linkNodes)
                {
                    string href = linkNode.GetAttributeValue("href", string.Empty);
                    if (Regex.IsMatch(href, pattern))
                    {
                        string feedUrl = BLOG_URI + href;
                        items.Add(new BlogData()
                        {
                            ID = blog.blogid,
                            BlogURL = blog.url,
                            Title = blog.blogName,
                            UserName = ConnectionString.UserName,
                            FeedURL = feedUrl,
                            PostURL = string.Empty,
                            SelfFeedURL = feedUrl
                        });
                    }
                }
            }

            return items;
        }

        public override IEnumerable<object> ExecuteQuery(object data)
        {
            BlogData blogdata = data as BlogData;
            RssFeedContext context = RssFeedContext.Create(blogdata.Url, blogdata.Title);
            foreach (PostData postData in context.Posts)
            {
                string linkString = postData.Link.ToString();
                int index = linkString.LastIndexOf('/');
                if (index != -1)
                {
                    string postidString = linkString.Substring(index + 1).Replace(".aspx", "");
                    try
                    {
                        Post post = Weblog.getPost(postidString, ConnectionString.UserName, ConnectionString.Password);
                        postData.Content = new PostContent()
                        {
                            Type = PostTextType.Html.ToString(),
                            Content = post.description
                        };
                    }
                    catch { }
                }

                yield return postData;
            }
        }
    }
}
